package middleware

import (
	"log"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)

var (
	requestCounter = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "http_requests_total",
			Help: "Total number of HTTP requests",
		},
		[]string{"method", "endpoint"},
	)

	requestDuration = prometheus.NewHistogramVec(
		prometheus.HistogramOpts{
			Name:    "http_request_duration_seconds",
			Help:    "Duration of HTTP requests",
			Buckets: prometheus.DefBuckets,
		},
		[]string{"method", "endpoint"},
	)
)

func init() {
	// 注册 Prometheus 指标
	prometheus.MustRegister(requestCounter)
	prometheus.MustRegister(requestDuration)
}

// PrometheusMiddleware Prometheus 监控中间件
func PrometheusMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()

		// 记录请求计数
		requestCounter.WithLabelValues(c.Request.Method, c.FullPath()).Inc()

		// 继续处理请求
		c.Next()

		// 记录请求耗时
		duration := time.Since(start).Seconds()
		requestDuration.WithLabelValues(c.Request.Method, c.FullPath()).Observe(duration)
	}
}

// RegisterPrometheus 注册 Prometheus 监控端点
func RegisterPrometheus(router *gin.Engine) {
	router.GET("api/metrics", gin.WrapH(promhttp.Handler()))
	log.Println("Prometheus 监控已启用，可通过 /api/metrics 访问")
}
